using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
//using System.Windows.Forms;
using System.Diagnostics;
using EForms;
using CStock;
using CGraph;
using CUtil;

namespace CapitalReSources
{
    /// <summary>
    /// Summary description for View.
    /// </summary>
    public partial class View : EForm, IView
    {
        #region Fields


        private IMainClass mainClass;
        private PersistWindowState persistWindowState;
        //private IMainClass mainClass;


        

        #endregion

        #region Constructors and Destructors

        public View(): base()
        {
            try
            {
                this.mainClass = MainClass.Instance;
                this.mainClass.View = this;
                InitializeComponent();


                this.mainClass.PropertyGrid = this.propertyGrid1;
                this.mainClass.TreeViewStock = this.treeViewStock;
                this.mainClass.TreeViewStock = this.treeViewStock;
                this.mainClass.TreeViewStock.InitTree(true);

                this.mainClass.TreeViewCustomPortfolios = this.treeViewCustomPorfolios;
                this.mainClass.TreeViewCustomPortfolios.InitTree(false);

                

                //default chart period = 2 years

                this.mainClass.ProgramContext.HelpProvider.SetShowHelp(this, true);

                this.persistWindowState = new PersistWindowState();
                persistWindowState.Parent = this;
                persistWindowState.RegistryPath = @"Software\Logisel\CapitalReSources";
                this.statusBarPanel1.TimeZone = 1;
                this.statusBarPanel2.TimeZone = -5;
                this.toolBarButtonIntraday.Pushed = this.mainClass.ProgramContext.Configuration.IntradayModus;

                this.propertyGrid1.ToolbarVisible = false;
                this.propertyGrid1.HelpBackColor = EForms.Themes.Colors.ApplicationBackground;
                this.propertyGrid1.LineColor = EForms.Themes.Colors.ApplicationBackground;


                // set registry path in HKEY_CURRENT_USER	
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error in View caught : " + ex.Message);
                //this occurs in design mode - do nothing
            }
            try
            {
                IProgramContext myProgramContext = this.mainClass.ProgramContext;
                if (myProgramContext != null)
                {

                    if (myProgramContext.TradeEconomy != null)
                    {
                        myProgramContext.TradeEconomy.Portfolio_Selected = myProgramContext.TradeEconomy.Portfolios[0];
                        this.mainClass.PropertyGrid.SelectedObject = myProgramContext.TradeEconomy.Portfolios[0];
                    }


                }
            }
            catch (Exception exc)
            {
                Debug.Assert(false, "Error initializing view " + exc.Message);
            }
        }

        #endregion

        #region IView

        public void SetIntradayButton()
        {
            this.toolBarButtonIntraday.Pushed = this.mainClass.ProgramContext.Configuration.IntradayModus;

        }

        #endregion

        #region properties

        public System.Windows.Forms.StatusBar StatusBar
        {
            get
            {
                return this.statusBar;
            }
        }
        #endregion

        #region FormView ToolBar

        private void toolbarButtonView_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
        {
            try
            {
                System.Windows.Forms.ToolBarButton locToolBarButton = e.Button;


                if (locToolBarButton == this.toolbarButtonToolsOptions)
                {
                    this.mainClass.DoMenuToolsOptions();
                }
                else if (locToolBarButton == this.toolBarButtonStopAction)
                {
                    this.mainClass.DoStopAction();
                }
                else if (locToolBarButton == this.toolBarButtonIntraday)
                {
                    this.mainClass.ProgramContext.Configuration.IntradayModusSilent = toolBarButtonIntraday.Pushed;
                }
                else if (locToolBarButton == this.toolbarButtonTradeSystem)
                {
                    this.mainClass.DoMenuTradeSystemBuySellChooseFile();
                    //this.mainClass.ProgramContext.Configuration.IntradayModusSilent = toolBarButtonIntraday.Pushed;
                }









                else
                {
                    Debug.WriteLine("View - Error recognizing ToolBarButton: Unknown ToolBarButton.");
                }
            }
            catch (Exception exc)
            {
                Debug.WriteLine("View - Error performing ToolBarButtonAction:  " + exc.Message);
                Debug.Assert(false, "View - Error performing ToolBarButtonAction: ", exc.Message);
            }
        }
        #endregion

        #region menus

        public System.Windows.Forms.MenuItem MenuItemChartIndicators
        {
            get
            {
                //return this.menuChartIndicators;
                return null;
            }
        }
        /// <summary>
        /// ContextMenuTreeView
        /// </summary>
        public System.Windows.Forms.ContextMenu ContextMenuTreeView
        {
            get
            {
                return contextMenuTreeView;
            }
        }


        private void contextMenuTreeView_Popup(object sender, System.EventArgs e)
        {
        }

        private void menuContextOptimize_Click(object sender, System.EventArgs e)
        {

            this.mainClass.DoMenuOptimize();

        }

        private void menuContextProperties_Click(object sender, System.EventArgs e)
        {

            this.mainClass.DoMenuProperties((object)treeViewStock.SelectedNode);


        }




        private void menuFileTest_Click(object sender, System.EventArgs e)
        {
            //no action yet ?
        }

        private void menuFileShareQuotes_Click(object sender, System.EventArgs e)
        {

        }
        private void menuHelpAbout_Click(object sender, System.EventArgs e)
        {
            this.mainClass.DoMenuHelpAbout();

        }

        private void menuToolsCustomize_Click(object sender, System.EventArgs e)
        {
            this.mainClass.DoMenuToolsCustomize();

        }
        private void menuToolsResetConfiguration_Click(object sender, System.EventArgs e)
        {
            this.mainClass.DoMenuResetConfiguration();

        }

        private void menuToolsOptions_Click(object sender, System.EventArgs e)
        {
            this.mainClass.DoMenuToolsOptions();

        }

        private void menuFileOpen_Click(object sender, System.EventArgs e)
        {

        }
        private void menuFileOpenExcel_Click(object sender, System.EventArgs e)
        {

            if (this.mainClass.ProgramContext.DoMenuOpenExcelFile())
                this.mainClass.RefreshTree();
        }
        private void menuFileOpenFromLocalDirectory_Click(object sender, System.EventArgs e)
        {
            this.mainClass.ProgramContext.TradeEconomy = null;
            this.mainClass.RefreshTree();

            if (this.mainClass.ProgramContext.GetProgramConfigurationFromDirectory())
            {
                this.mainClass.UpdateViewCurrentPath();
                this.mainClass.RefreshTree();
            }
          
        }



        private void menuTradeTradeSystem_Click(object sender, System.EventArgs e)
        {

        }
        //
        private void menuViewChart_Click(object sender, System.EventArgs e)
        {
            this.mainClass.DoMenuChartControl(this.mainClass.ProgramContext.Configuration.IntradayModus);


        }



        private void menuModeUserTrade_Click(object sender, System.EventArgs e)
        {
            this.mainClass.DoModeUserTrade();

        }
        private void menuAddOneDay_Click(object sender, System.EventArgs e)
        {
            this.mainClass.DoMenuAddOneDay();
        }
        private void menuSaveExcel_Click(object sender, System.EventArgs e)
        {
            this.mainClass.SaveInExcel();
        }

        private void menuXMLGet_Click(object sender, System.EventArgs e)
        {
            object o = null;
            XMLSerializable x = new XMLSerializable();
            x.Name = "xx"; //the file name is built after this - with .xml extension
            o = x;
            x.DeSerialize(ref o);

            XMLSerializable xx1 = new XMLSerializable();
            xx1.Name = "xx";
            o = (object)xx1;
            xx1.DeSerialize(ref o);
            XMLSerializable ixoo = o as XMLSerializable;

            o = (object)x;
            x.DeSerialize(ref o);
            //XMLSerializable ix = o as XMLSerializable;

           

            DataItem di = new DataItem();
            di.DataClass = new DataClassDaily();
            di.DataClass.ID = "22222";

            di.DataClass.Serialize();





            o = (object)di.DataClass;
            if (di.DataClass.DeSerialize(ref o))
            {
                //do nothing
                //IDataClass idc = o as IDataClass;

            }

            DataItem dci = new DataItem();

            o = (object)dci;
            Portfolio actualPortfolio = new Portfolio();
            actualPortfolio.Name = "030_Demo";


            Portfolio newP = new Portfolio();
            newP.Name = "030_Demo";

            o = (object)newP;
            actualPortfolio.DeSerialize(ref o);
            IPortfolio port = o as IPortfolio;
            System.Diagnostics.Debug.Assert(port != null);
            if (port == null)
                return;



        }

        private void menuQuit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        //private void menuNewPortfolio_Click(object sender, System.EventArgs e)
        //{
        //    this.mainClass.DoMenuNewPorfolio();
        //}

        #endregion

        #region XmlTest

        /// <summary>
        /// menuXmlSerialization_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuXmlSerialization_Click(object sender, System.EventArgs e)
        {
            this.TestPortfolioXmlSerialization();
        }
        /// <summary>
        /// TestPortfolioXmlSerialization
        /// </summary>
        private void TestPortfolioXmlSerialization()
        {
            try
            {
                string locSerPath = this.mainClass.ProgramContext.Configuration.Directories.ApplicationPath;
                //= this.mainClass.ProgramContext.Configuration.WorkingDirectory;
                // Share Serialization

                IXMLSerializable s = new StockObjectBase();//this.mainClass.ProgramContext.Configuration as IXMLSerializable;
                s.ID = "Configuration";
                s.Serialize();

                IXMLSerializable c = this.mainClass.ProgramContext.Configuration as IXMLSerializable;
                c.ID = "Configuration";
                c.Serialize();


                IDataClass dc = new DataClassDaily();
                dc.ID = "22222";
                dc.QuoteCollection.Add(new Quote());
                //dc.WKN = 22222;


                dc.Serialize();


                DataItem dci = new DataItem();
                dci.DataClass = dc;
                dci.Serialize();
                // Portfolio Serialization
                IPortfolio ipf = new Portfolio();
                ipf.StockTypePortfolio = false;
                //= this.mainClass.ProgramContext.Portfolio;
                Portfolio pf = (Portfolio)ipf;
                CStock.DataItems locDataItems = new CStock.DataItems();
                for (int i = 0; i < this.mainClass.ProgramContext.TradeEconomy.Portfolios[0].DataItems.Count; i++)
                {
                    locDataItems.Add(this.mainClass.ProgramContext.TradeEconomy.Portfolios[0].DataItems[i], this.mainClass.ProgramContext.TradeEconomy.Portfolios[0]);
                }

                pf.DataItems = locDataItems;
                IXMLSerializable pser = pf as IXMLSerializable;
                if (pser != null)
                {
                    pser.ID = "xxxPortfolio";
                    pser.Serialize();
                }

                pf = null;
                pf = this.mainClass.ProgramContext.TradeEconomy.Portfolios[0] as Portfolio;
                pser = pf as IXMLSerializable;
                if (pser != null)
                {
                    pser.ID = "xxxNewPort";

                    pser.Serialize();
                }

            }
            catch (Exception exc)
            {
                Debug.Assert(false, "View - Error serializing Portfolio: ", exc.Message);
            }
        }

        #endregion

        #region status bar

        // Resize status bar (keep all panels except first in right side).
        private void ResizeStatusBar()
        {
            int n = statusBar.Panels.Count;

            if (n > 1)
            {
                int nRightWidth = 0;    // width of panels 1,2...

                for (int i = 1; i < n; i++)
                {
                    nRightWidth += statusBar.Panels[i].Width;
                }

                if (statusBar.Panels[0].MinWidth < statusBar.Width - nRightWidth)
                {
                    statusBar.Panels[0].Width = statusBar.Width - nRightWidth;
                }
            }
        }


        public void SetStatusBarText(int panelNumber, string text)
        {
            StatusBarPanel pan = this.statusBar.Panels[panelNumber] as StatusBarPanel;
            pan.Text = text;
        }

        #endregion

        #region other menus

        private void DoMenuUpdateStandardPorfolios_OnlyQuotes_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuUpdateStandardPorfolio_Quotes();
        }

        private void menuContextUpdateStandardPortfolio_Names_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuUpdateStandardPorfolio_Names();
        }

        private void menuContextUpdateStandardPortfolio_Quotes_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuUpdateStandardPorfolio_Quotes();
        }

        private void menuContextIntradayQuoteLast_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuIntradayQuoteLast();
        }
        private void menuContextPortfolioShowInGrid_Click(object sender, EventArgs e)
        {
            this.mainClass.DoTreeMenuMenuPortfolioShowInGrid();
        }

      
        private void menuItemIntraday_WhichQuotesFetched_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuIntradayQuotes_WhichQuotesFetched();
        }

        private void menuItemIntraday_Start_GetQuotes_Click(object sender, EventArgs e)
        {

            this.mainClass.DoMenuIntradayQuotes_StartGet_All();
        }

        private void menuItemIntraday_Stop_GetQuotes_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuIntradayQuotes_StopGet_All();
        }

      

        protected override void Dispose(bool disposing)
        {
            //this.mainClass.DoMenuIntradayQuotes_StopGet_All();
            base.Dispose(disposing);
        }

        private void menuItemNews_Click(object sender, EventArgs e)
        {
            //this.mainClass.DoMenuNews();
        }

        private void menuIntradayLoopStart_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuGetIntradayDataStart();
        }

        private void menuIntradayLoopStop_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuGetIntradayDataStop();
        }

        private void menuChartIntraday_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuChartIntraday();
        }

        private void menuResetPortfolioWeb_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuResetPortfolioFromWeb();
        }

        private void menuItemUpdateLast_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuUpdateFinancialData();
        }

        private void menuItemPortfolioNew_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuNewPorfolio();
            this.tabControlTreeViews.SelectedIndex = 1;

        }


        private void handlerAddAssetToPortfolio(object sender, EventArgs e)
        {
            EForms.MenuItem mi = sender as EForms.MenuItem;
            string portfolioCustomName = mi.Text;

            this.mainClass.AddAssetToCustomPortfolio(portfolioCustomName);
            //this.menuItemAddToIntradayFetchList
            


        }
        private void menuItemAddAssetToPortfolio_Select(object sender, EventArgs e)
        {
            for (int i = 0; i < menuItemAddAssetToPortfolio.MenuItems.Count; i++)
            {
                EForms.MenuItem mi = menuItemAddAssetToPortfolio.MenuItems[i] as EForms.MenuItem;
                mi.Click -= new System.EventHandler(this.handlerAddAssetToPortfolio);

            }
            menuItemAddAssetToPortfolio.MenuItems.Clear();
            IPortfolios ports = this.mainClass.Portfolios_Custom();
            for (int i = 0; i < ports.Items.Count; i++)
            {
                IPortfolio port = ports.Items[i] as IPortfolio;
                EForms.MenuItem mi = new MenuItem();
                mi.Text = port.Name;
                //mi.Tag = port;
                menuItemAddAssetToPortfolio.MenuItems.Add(mi);
                mi.Click += new System.EventHandler(this.handlerAddAssetToPortfolio);
            }

        }

        private void menuItemFundamentalData_Click(object sender, EventArgs e)
        {

            this.mainClass.DoMenuUpdateFundamentalData_Years();
        }

        #endregion

        private void menuItemFundamentalData_Quartals_Click(object sender, EventArgs e)
        {
            this.mainClass.DoMenuUpdateFundamentalData_Quarter();
        }
    }
}
